<template>
  <el-dialog :title="title" :visible.sync="visible" @closed="closedHandler">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="name" label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="description"
        label="角色描述"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRole, editRoleById } from '../../../api/setting'
export default {
  name: 'SettingDialog',
  data() {
    return {
      visible: false,
      formLabelWidth: '120px',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    closedHandler() {
      this.form = { name: '', description: '' }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            await editRoleById(this.form)
            this.$message.success('修改成功！')
          } else {
            await addRole(this.form)
            //   console.log(res)
            this.$message.success('新增成功！')
          }

          this.visible = false
          this.form = { name: '', description: '' }
          this.$parent.getData()
        } else {
          this.$message.error('输入有误，请检查！')
          return false
        }
      })
    }
  }
}
</script>

<style></style>
